package com.guaoran.distributed.sentinel.demo;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @Author gucheng
 * @Description Semaphore 限流
 * 2019-05-21 13:44
 */
public class SemaphoreDemo extends Thread{
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(5);
        for (int i = 0; i < 100; i++) {
            new SemaphoreDemo(i,semaphore).start();
        }
    }

    private int i;
    private Semaphore semaphore;

    public SemaphoreDemo(int i, Semaphore semaphore) {
        this.i = i;
        this.semaphore = semaphore;
    }

    @Override
    public void run() {
        try {
            semaphore.acquire();
            System.out.println("第"+i+"个程序进来了。。。。");
            TimeUnit.SECONDS.sleep(1);
            semaphore.release();
            System.out.println(i+"出去了");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
